<?php

namespace app\controller\admin\lineup;

use app\model\admin\lineup\LineupGame;
use app\model\admin\lineup\LineupStyle;
use app\model\admin\lineup\LineupStyleLabelRelation;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Style extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info'];
    protected $type = 1;
    public function initialize()
    {
        $this->model = new LineupStyle();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $searchParam = $this->request->param('search_param');
            $limit = $this->request->param('limit', 10);
            $data = $this->model->where($where)->order($order)->paginate($limit)->toArray();
            $domainUrl = (new LineupGame())->where('id',$searchParam['lineup_game_id']['value'])->value("domain_url");
            foreach ($data['data'] as &$item) {
                $item['url'] = $domainUrl."/preview/".$item['id'];
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        if (!$this->request->param("game_id")) {
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        $post = CommonFun::filterPostData($this->request->post());
        $relation_ids_1 = "";
        $relation_ids_2 = "";
        $relation_ids_3 = "";
        $relation_ids_4 = "";
        if (isset($post['laytpUploadFile'])) unset($post['laytpUploadFile']);
        if(isset($post['relation_ids_1']))$relation_ids_1 = $post['relation_ids_1'];unset($post['relation_ids_1']);
        if(isset($post['relation_ids_2']))$relation_ids_2 = $post['relation_ids_2'];unset($post['relation_ids_2']);
        if(isset($post['relation_ids_3']))$relation_ids_3 = $post['relation_ids_3'];unset($post['relation_ids_3']);
        if(isset($post['relation_ids_4']))$relation_ids_4 = $post['relation_ids_4'];unset($post['relation_ids_4']);
        try {
            Db::startTrans();
            $post['lineup_game_id'] = $gameId;
            $post['create_time'] = date("Y-m-d H:i:s");
            $post['update_time'] = date("Y-m-d H:i:s");
            $id = $this->model->insertGetId($post);
            if ($id) {
                $relations = [];
                if(!empty($relation_ids_1)){
                    foreach (explode(",",$relation_ids_1) as $item){
                        $relations[] = [
                          'lineup_style_id'=>$id,
                          'type'=>1,
                          'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($relation_ids_2)){
                    foreach (explode(",",$relation_ids_2) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>2,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($relation_ids_3)){
                    foreach (explode(",",$relation_ids_3) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>3,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($relation_ids_4)){
                    foreach (explode(",",$relation_ids_4) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>4,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(count($relations)>0){
                    (new LineupStyleLabelRelation())->insertAll($relations);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                (new LineupStyleLabelRelation())->where('lineup_style_id', $id)->delete();
                $relations = [];
                if(!empty($post['relation_ids_1'])){
                    foreach (explode(",",$post['relation_ids_1']) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>1,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($post['relation_ids_2'])){
                    foreach (explode(",",$post['relation_ids_2']) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>2,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($post['relation_ids_3'])){
                    foreach (explode(",",$post['relation_ids_3']) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>3,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(!empty($post['relation_ids_4'])){
                    foreach (explode(",",$post['relation_ids_4']) as $item){
                        $relations[] = [
                            'lineup_style_id'=>$id,
                            'type'=>4,
                            'label_id'=>$item,
                        ];
                    }
                }
                if(count($relations)>0){
                    (new LineupStyleLabelRelation())->insertAll($relations);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if(is_object($info))$info = $info->toArray();
        $list = (new LineupStyleLabelRelation())->where("lineup_style_id",$id)->select()->toArray();
        $relations = [];
        foreach ($list as $item){
            $relations[$item['type']][] = $item['label_id'];
        }
        foreach ($relations as $key=>$item){
            $info['relation_ids_'.$key] = implode(",",$item);
        }
        $info['basic_game_id'] = (new LineupGame())->where('id',$info['lineup_game_id'])->value("basic_game_id");
        return $this->success('获取成功', $info);
    }

    //设置排序
    public function setStatus()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['status'] = $fieldVal;

        try {
            if($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                if($update['status']==1){
                    $lineup_game_id = $this->model->where('id', '=', $id)->value("lineup_game_id");
                    if($lineup_game_id){
                        $this->model->where('lineup_game_id', '=', $lineup_game_id)->update(['status'=>2]);
                    }
                }
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }
}